/*
Copyright (C) Vincenzo Tilotta 2012 <tailot@gmail.com>

cookie.js is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option) any later version.

cookie.js is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
function Cookie(){
	this.db = '';
	this.init = function(){
		this.db = window.openDatabase("cookie", "1.0", "cookie", 200000);
		this.db.transaction(this.populateDB, this.errorCB, this.successCB);
	};
	this.populateDB = function(tx) {
	    tx.executeSql('CREATE TABLE IF NOT EXISTS cookies (name NOT NULL PRIMARY KEY, value)');      
	};
	this.setCookie = function(name, value){
		this.db.transaction(function(tx){
			tx.executeSql('INSERT INTO cookies (name,value) VALUES ("'+name+'","'+value+'")');
		}, this.updateValue(name, value), this.successCB);
	};
	this.getCookie = function(name,idelement){
		this.db.transaction(function(tx){
			tx.executeSql('SELECT * FROM cookies WHERE name="'+name+'"',[], function(tx, results){
				var len = results.rows.length;
				for (var i=0; i<len; i++){
					$('#'+idelement).html(results.rows.item(i).value);
				}
			}, this.errorCB);
		}, this.errorCB);	
	};
	this.destroyCookie = function(name){
		this.db.transaction(function(tx){
			tx.executeSql("DELETE FROM cookies WHERE name = '"+name+"'",[],function(tx, results){
			});
		}, this.errorCB, this.successCB);
	};
	this.updateValue = function(name, value){
		this.db.transaction(function(tx){
			tx.executeSql("UPDATE cookies SET value='"+value+"' WHERE name='"+name+"'");
		}, this.errorCB, this.successCB);		
	};
	//Error function
	this.errorCB = function(){
		console.log("Errore nel db");
	};
	this.successCB = function(){
		console.log("Successo nella query");
	};
	//--------
	this.init();
}